using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using AutoStartManager.Models;
using AutoStartManager.Services;

namespace AutoStartManager
{
    public partial class ProcessSelectionDialog : Form
    {
        public ManagedApp ManagedApp { get; private set; }

        private DataGridView _processDataGridView;
        private TextBox _nameTextBox;
        private TextBox _argumentsTextBox;
        private TextBox _workingDirectoryTextBox;
        private CheckBox _enabledCheckBox;
        private Button _okButton;
        private Button _cancelButton;
        private Button _refreshButton;
        private List<ProcessInfo> _processes;

        public ProcessSelectionDialog(List<ProcessInfo> processes)
        {
            _processes = processes;
            ManagedApp = new ManagedApp();
            InitializeComponent();
            LoadProcesses();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // 设置窗体属性
            this.Text = "从运行进程添加应用";
            this.Size = new Size(700, 500);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 创建主面板
            var mainPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 1,
                RowCount = 4,
                Padding = new Padding(10)
            };

            // 设置行高
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 40));
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 60));
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 40));
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 40));

            // 工具栏
            var toolbarPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Height = 40
            };

            _refreshButton = new Button
            {
                Text = "刷新进程列表",
                Size = new Size(120, 25),
                Location = new Point(10, 8)
            };
            _refreshButton.Click += RefreshButton_Click;

            toolbarPanel.Controls.Add(_refreshButton);

            // 进程列表
            _processDataGridView = new DataGridView
            {
                Dock = DockStyle.Fill,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = false,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                BackgroundColor = SystemColors.Window,
                BorderStyle = BorderStyle.Fixed3D
            };

            _processDataGridView.Columns.Add("Id", "进程ID");
            _processDataGridView.Columns.Add("Name", "进程名");
            _processDataGridView.Columns.Add("MainWindowTitle", "窗口标题");
            _processDataGridView.Columns.Add("StartTime", "启动时间");
            _processDataGridView.Columns.Add("ExecutablePath", "可执行文件路径");

            _processDataGridView.Columns["Id"].Width = 80;
            _processDataGridView.Columns["Name"].Width = 120;
            _processDataGridView.Columns["StartTime"].Width = 120;

            _processDataGridView.SelectionChanged += ProcessDataGridView_SelectionChanged;

            // 应用信息面板
            var appInfoPanel = new GroupBox
            {
                Text = "应用信息",
                Dock = DockStyle.Fill
            };

            var appInfoTable = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 4,
                Padding = new Padding(10)
            };

            appInfoTable.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 100));
            appInfoTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));

            for (int i = 0; i < 4; i++)
            {
                appInfoTable.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
            }

            // 应用名称
            var nameLabel = new Label
            {
                Text = "应用名称:",
                TextAlign = ContentAlignment.MiddleLeft,
                Anchor = AnchorStyles.Left
            };
            _nameTextBox = new TextBox
            {
                Anchor = AnchorStyles.Left | AnchorStyles.Right
            };

            // 启动参数
            var argumentsLabel = new Label
            {
                Text = "启动参数:",
                TextAlign = ContentAlignment.MiddleLeft,
                Anchor = AnchorStyles.Left
            };
            _argumentsTextBox = new TextBox
            {
                Anchor = AnchorStyles.Left | AnchorStyles.Right
            };

            // 工作目录
            var workingDirectoryLabel = new Label
            {
                Text = "工作目录:",
                TextAlign = ContentAlignment.MiddleLeft,
                Anchor = AnchorStyles.Left
            };
            _workingDirectoryTextBox = new TextBox
            {
                Anchor = AnchorStyles.Left | AnchorStyles.Right
            };

            // 启用状态
            _enabledCheckBox = new CheckBox
            {
                Text = "启用监控",
                Checked = true,
                Anchor = AnchorStyles.Left
            };

            appInfoTable.Controls.Add(nameLabel, 0, 0);
            appInfoTable.Controls.Add(_nameTextBox, 1, 0);
            appInfoTable.Controls.Add(argumentsLabel, 0, 1);
            appInfoTable.Controls.Add(_argumentsTextBox, 1, 1);
            appInfoTable.Controls.Add(workingDirectoryLabel, 0, 2);
            appInfoTable.Controls.Add(_workingDirectoryTextBox, 1, 2);
            appInfoTable.Controls.Add(_enabledCheckBox, 1, 3);

            appInfoPanel.Controls.Add(appInfoTable);

            // 按钮面板
            var buttonPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.RightToLeft,
                Height = 40,
                Padding = new Padding(10, 8, 10, 8)
            };

            _cancelButton = new Button
            {
                Text = "取消",
                Size = new Size(80, 25),
                DialogResult = DialogResult.Cancel
            };
            _cancelButton.Click += CancelButton_Click;

            _okButton = new Button
            {
                Text = "确定",
                Size = new Size(80, 25),
                Margin = new Padding(0, 0, 10, 0)
            };
            _okButton.Click += OkButton_Click;

            // 注意：先添加取消按钮，因为FlowDirection是RightToLeft
            buttonPanel.Controls.Add(_cancelButton);
            buttonPanel.Controls.Add(_okButton);

            // 添加到主面板
            mainPanel.Controls.Add(toolbarPanel, 0, 0);
            mainPanel.Controls.Add(_processDataGridView, 0, 1);
            mainPanel.Controls.Add(appInfoPanel, 0, 2);
            mainPanel.Controls.Add(buttonPanel, 0, 3);

            this.Controls.Add(mainPanel);
            
            // 设置默认按钮
            this.AcceptButton = _okButton;
            this.CancelButton = _cancelButton;
            
            this.ResumeLayout(false);
        }

        private void LoadProcesses()
        {
            _processDataGridView.Rows.Clear();
            foreach (var process in _processes)
            {
                _processDataGridView.Rows.Add(
                    process.Id,
                    process.Name,
                    process.MainWindowTitle,
                    process.StartTime.ToString("HH:mm:ss"),
                    process.ExecutablePath
                );
            }
        }

        private void ProcessDataGridView_SelectionChanged(object? sender, EventArgs e)
        {
            if (_processDataGridView.SelectedRows.Count > 0)
            {
                var selectedIndex = _processDataGridView.SelectedRows[0].Index;
                var process = _processes[selectedIndex];

                // 自动填充信息
                _nameTextBox.Text = process.Name;
                _workingDirectoryTextBox.Text = System.IO.Path.GetDirectoryName(process.ExecutablePath) ?? "";
                _argumentsTextBox.Text = ""; // 进程参数无法直接获取
            }
        }

        private void RefreshButton_Click(object? sender, EventArgs e)
        {
            try
            {
                // 重新获取进程列表
                var processMonitor = new ProcessMonitor(new ConfigManager());
                _processes = processMonitor.GetRunningProcesses();
                LoadProcesses();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新进程列表失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OkButton_Click(object? sender, EventArgs e)
        {
            // 首先检查是否选择了进程
            if (_processDataGridView.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择一个进程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 然后验证其他输入
            if (ValidateInput())
            {
                var selectedIndex = _processDataGridView.SelectedRows[0].Index;
                var process = _processes[selectedIndex];

                ManagedApp.Name = _nameTextBox.Text.Trim();
                ManagedApp.ExecutablePath = process.ExecutablePath;
                ManagedApp.Arguments = _argumentsTextBox.Text.Trim();
                ManagedApp.WorkingDirectory = _workingDirectoryTextBox.Text.Trim();
                ManagedApp.IsEnabled = _enabledCheckBox.Checked;

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void CancelButton_Click(object? sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(_nameTextBox.Text))
            {
                MessageBox.Show("请输入应用名称", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _nameTextBox.Focus();
                return false;
            }

            if (!string.IsNullOrWhiteSpace(_workingDirectoryTextBox.Text) && !System.IO.Directory.Exists(_workingDirectoryTextBox.Text))
            {
                MessageBox.Show("指定的工作目录不存在", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _workingDirectoryTextBox.Focus();
                return false;
            }

            return true;
        }
    }
}